domain = "demo.worketc.com";
portalName = "Demo";
sessionKey = "VeetroSession";
userId = "";
userHashId = "";
ticketsPageSize = 5;
pagerCallReload = false;


// Creates a cookie and stores it in the document cookies collection
function createCookie(name, value, days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
		var expires = "; expires=" + date.toGMTString();
	} else
		var expires = "";
	document.cookie = name + "=" + value + expires + "; path=/";
}

// Reads a cookie by name from the document cookie collection
function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for ( var i = 0; i < ca.length; i++) {
		var c = ca[i];
		while (c.charAt(0) == ' ')
			c = c.substring(1, c.length);
		if (c.indexOf(nameEQ) == 0)
			return c.substring(nameEQ.length, c.length);
	}
	return null;
}

// Removes a cookie by name from the browser cookie collection
function eraseCookie(name) {
	createCookie(name, "", -1);
}

(function($) {
	var m = {
		'\b' : '\\b',
		'\t' : '\\t',
		'\n' : '\\n',
		'\f' : '\\f',
		'\r' : '\\r',
		'"' : '\\"',
		'\\' : '\\\\'
	}, s = {
		'array' : function(x) {
			var a = [ '[' ], b, f, i, l = x.length, v;
			for (i = 0; i < l; i += 1) {
				v = x[i];
				f = s[typeof v];
				if (f) {
					v = f(v);
					if (typeof v == 'string') {
						if (b) {
							a[a.length] = ',';
						}
						a[a.length] = v;
						b = true;
					}
				}
			}
			a[a.length] = ']';
			return a.join('');
		},
		'boolean' : function(x) {
			return String(x);
		},
		'null' : function(x) {
			return "null";
		},
		'number' : function(x) {
			return isFinite(x) ? String(x) : 'null';
		},
		'object' : function(x) {
			if (x) {
				if (x instanceof Array) {
					return s.array(x);
				}
				// Special JSON date hack for MS based service
				if (x instanceof Date) {
					return '"\\\/Date(' + x.getTime() + ')\\\/"';
				}
				var a = [ '{' ], b, f, i, v;
				for (i in x) {
					v = x[i];
					f = s[typeof v];
					if (f) {
						v = f(v);
						if (typeof v == 'string') {
							if (b) {
								a[a.length] = ',';
							}
							a.push(s.string(i), ':', v);
							b = true;
						}
					}
				}
				a[a.length] = '}';
				return a.join('');
			}
			return 'null';
		},
		'string' : function(x) {
			if (/["\\\x00-\x1f]/.test(x)) {
				x = x.replace(/([\x00-\x1f\\"])/g, function(a, b) {
					var c = m[b];
					if (c) {
						return c;
					}
					c = b.charCodeAt();
					return '\\u00' + Math.floor(c / 16).toString(16)
							+ (c % 16).toString(16);
				});
			}
			return '"' + x + '"';
		}
	};

	$.toJSON = function(v) {
		var f = isNaN(v) ? s[typeof v] : s['number'];
		if (f)
			return f(v);
	};

	$.parseJSON = function(v, safe) {
		if (safe === undefined)
			safe = $.parseJSON.safe;
		if (safe
				&& !/^("(\\.|[^"\\\n\r])*?"|[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t])+?$/
						.test(v))
			return undefined;
		return eval('(' + v + ')');
	};

	$.parseJSON.safe = false;

})(jQuery);

// A very important workaround for IE!
// It replaces the default transport object of jQuery, which is XmlHTTPRequest
// by the IE specific XDomainRequest
// This solves the XSS issue
$
		.ajaxTransport(
				"+*",
				function(options, originalOptions, jqXHR) {

					if (true && jQuery.browser.msie && window.XDomainRequest) {

						var xdr;

						return {

							send : function(headers, completeCallback) {

								// Use Microsoft XDR
								xdr = new XDomainRequest();

								xdr.open("post", options.url);

								xdr.onload = function() {
									completeCallback(200, "success",
											[ this.responseText ]);
								};

								xdr.ontimeout = function() {
									completeCallback(408, "error",
											[ "The request timed out." ]);
								};

								xdr.onerror = function() {
									completeCallback(
											404,
											"error",
											[ "The requested resource could not be found." ]);
								};

								xdr.send(options.data);
							},
							abort : function() {
								if (xdr)
									xdr.abort();
							}
						};
					}
				});

// Does the very first login request
// On success: stores the session key as a cookie and
// continues requesting the logged in customer's data (personal data and
// tickets)
function LoginAndDoStuff(domain, email, pass) {
	// Construct login paramaters (see /Xml?op=AuthenticateWebSafe for docs)
	var request = new Object();
	request.email = email;
	request.pass = pass;

	$.ajax({
		url : 'http://' + domain + '/Json/AuthenticateWebSafe',
		type : 'POST',
		dataType : 'json',
		contentType : 'application/json; charset=utf-8',
		data : $.toJSON(request),
		success : function(result) {
			if (result.Code == 1) {
				createCookie(sessionKey, result.SessionKey);
				userId = result.User.EntityID;
				userHashId = result.User.EntityHashID;
				$("#wt_business_name").text(portalName);
				readCustomerData();
				readTicketsFull(0);
			} else {
				alert(result.Message);
			}
		}
	});
}

// Reads the personal customer data
// On success: adds Customer data fields as table rows of html table
// #wt_customer_data_tb
function readCustomerData() {

	var request = new Object();
	request.EntityID = userId;
	request.fullDetails = "true";

	$.ajax({
		url : 'http://' + domain + '/Json/GetPerson?VeetroSession='
				+ readCookie(sessionKey),
		type : 'POST',
		dataType : 'json',
		crossDomain : "true",
		data : $.toJSON(request),
		contentType : 'application/json; charset=utf-8',
		success : function(result) {
			$("#wt_customer_info").show();
			$("#wt_login").hide();
			$("#wt_customer_name").text(result.Title + " " + result.Name);
			$.each(result.Addresses, function(i, address) {
				// AddressType 1 - Work
				if (1 == address.AddressType) {
					appendDataRow("#wt_customer_data_tb", "Street",
							address.Street);
					appendDataRow("#wt_customer_data_tb", "City",
							address.Suburb + " " + address.PostalCode);
					appendDataRow("#wt_customer_data_tb", "Country",
							address.Country);
					appendDataRow("#wt_customer_data_tb", "Work phone",
							address.Phone);
					appendDataRow("#wt_customer_data_tb", "", "&nbsp;", true);
				}
			});
			appendDataRow("#wt_customer_data_tb", "E-Mail", result.Email);
			appendDataRow("#wt_customer_data_tb", "Mobile", result.Mobile);
			appendDataRow("#wt_customer_data_tb", "Website", result.Website);
			$.each(result.RelatedBranches, function(i, val) {
				addCompany(val.BranchName);
				// getBranchAddress(val.EntityID, val.BranchID, val.BranchName,
				// i);
			});
		},
		error : function(xhr, ajaxOptions, thrownError) {
			alert(xhr.responseText);
			alert(xhr.statusText);
		}
	});
}

// Reads branch address by company id and branch id
// On success: appends a row with branch address to the table
// #wt_customer_data_tb
function getBranchAddress(companyId, branchId, branchName, companyNumber) {
	var request = new Object();
	request.EntityID = companyId;
	request.fullDetails = "true";

	$.ajax({
		url : 'http://' + domain + '/Json/GetCompany?VeetroSession='
				+ readCookie(sessionKey),
		type : 'POST',
		dataType : 'json',
		crossDomain : "true",
		data : $.toJSON(request),
		contentType : 'application/json; charset=utf-8',
		success : function(result) {
			$.each(result.Branches, function(i, val) {
				if (val.BranchID == branchId) {
					addCompany(branchName, val.Addresses[0]);
				}
			});
			return null;
		},
		error : function(xhr, ajaxOptions, thrownError) {
			alert(xhr.responseText);
			alert(xhr.statusText);
		}
	});
}

function addCompany(branchName, branchAddress) {
	var companyInfo = $("<div>");
	companyInfo.text(branchName);
	$("#wt_cd_companies").append(companyInfo);
}

// Helper method for appending a two-cells row to a given table.
// The two cells represent a label and a value
// If isHtml = true, the value is applied as html, otherwise as plain text
function appendDataRow(table, label, value, isHtml) {
	if (value != null && value != "") {
		var row = $("<tr>");
		row.append($("<th>").text(label));
		if (isHtml)
			row.append($("<td>").html(value));
		else
			row.append($("<td>").text(value));
		$(table).append(row);
	}
}

function getStatusPresenter(status) {
	var statusPresenter = new Object();

	switch (status) {
	case 0:
		statusPresenter.cssClass = "ticketNew";
		statusPresenter.txt = "New";
		break;
	case 1:
		statusPresenter.cssClass = "ticketOpen";
		statusPresenter.txt = "Open";
		break;
	case 2:
		statusPresenter.cssClass = "ticketClosed";
		statusPresenter.txt = "Closed";
		break;
	case 3:
		statusPresenter.cssClass = "ticketReplied";
		statusPresenter.txt = "Replied";
		break;

	}
	return statusPresenter;
}

// Helper method for applying html class to a ticket element dependent on the
// ticket priority
function getPriorityPresenter(priority) {
	var priorityPresenter = new Object();

	// 0 - none, 1 - ???, 2 - high, 3 - medium, 4 - low

	switch (priority) {
	case 0:
		priorityPresenter.cssClass = "ticketPrioNone";
		priorityPresenter.txt = "None";
		break;
	case 1:
		priorityPresenter.cssClass = "ticketPrioNone";
		priorityPresenter.txt = "None";
		break;
	case 2:
		priorityPresenter.cssClass = "ticketPrioHigh";
		priorityPresenter.txt = "High";
		break;
	case 3:
		priorityPresenter.cssClass = "ticketPrioMedium";
		priorityPresenter.txt = "Medium";
		break;
	case 4:
		priorityPresenter.cssClass = "ticketPrioLow";
		priorityPresenter.txt = "Low";
		break;
	}

	return priorityPresenter;
}

// Reads all tickets issued by the currently logged in customer
// On success : Adds the tickets as list items to unordered list #wt_tickets
function readTicketsFull(startPage) {

	var e = new Object();
	e.StartIndex = startPage * ticketsPageSize;
	e.FetchSize = ticketsPageSize;
	e.Types = "Support_Case";
	e.Sort = "Priority";
	e.EntityID_Relation = userId;
	e.SortAsc = "true"

	var request = new Object();
	request.e = e;

	$
			.ajax({
				url : 'http://' + domain
						+ '/Json/GetCalendarViewDataPaged?VeetroSession='
						+ readCookie(sessionKey),
				type : 'POST',
				dataType : 'json',
				crossDomain : "true",
				data : $.toJSON(request),
				contentType : 'application/json; charset=utf-8',
				success : function(result) {
					$(".ticket-data-row").remove();
					if (result.Results.length > 0) {
						$("#wt_support_cases").show();
						allTickets = result.Results;						
						populatePager(result.RecordCount, startPage + 1);
						$.each(
										result.Results,
										function(i, val) {
											var ticketName = $("<td><a href='#' onclick='javascript:showTicketDetails("
													+ val.PrimaryKey
													+ ")'>"
													+ val.Name + "</a></td>");
											var priorityPresenter = getPriorityPresenter(val.Priority);
											var statusPresenter = getStatusPresenter(val.SupportCaseStatus);
											var ticketPriority = $("<td>");
											ticketPriority
													.text(priorityPresenter.txt);
											ticketPriority
													.addClass(priorityPresenter.cssClass);
											var ticketStatus = $("<td>");
											ticketStatus
													.text(statusPresenter.txt);
											ticketStatus
													.addClass(statusPresenter.cssClass);
											var listItem = $("<tr class='ticket-data-row'>");
											listItem.append(ticketName);
											listItem.append(ticketPriority);
											listItem.append(ticketStatus);
											$("#wt_tickets").append(listItem);
										});
					}
				},
				error : function(xhr, ajaxOptions, thrownError) {
					alert(xhr.responseText);
					alert(xhr.statusText);
				}
			});
}

function populatePager(elementsNumber, initialPage){
	pagerCallReload = false;
	$("#pagination").paging(elementsNumber, {
        format: '[< ncnnn >]',
        perpage: ticketsPageSize,
        page: initialPage,
        onSelect: function (page) {
              if(true == pagerCallReload)
            	  readTicketsFull(page - 1);
              pagerCallReload = true;
        },
        onFormat: function (type) {
                switch (type) {
                case 'block': // n and c
                        return '<li><a>' + this.value + '</a></li>';
                case 'next': // >
                        return '<li><a>&raquo;</a></li>';
                case 'prev': // <
                        return '<li><a>&laquo;</a></li>';
                case 'first': // [
                        return '<li><a><b>|&lt;</b></a></li>';
                case 'last': // ]
                        return '<li><a><b>|&gt;</b></a></li>';
                }
        }
});
}

function showTicketDetails(ticketId) {
	$.each(allTickets, function(i, ticket) {
		if (ticketId == ticket.PrimaryKey) {
			populateTicketDetailsDialog(ticket);
			$("#wt_td_dialog").dialog({
				width : 450
			});
		}
	});
}

function populateTicketDetailsDialog(ticket) {
	$("#wt_td_name").text(ticket.Name);
	var priorityPresenter = getPriorityPresenter(ticket.Priority);
	var statusPresenter = getStatusPresenter(ticket.SupportCaseStatus);
	$("#wt_td_priority").text(priorityPresenter.txt);
	$("#wt_td_priority").removeClass(
			"ticketPrioNone ticketPriohigh ticketPrioMedium ticketPrioLow")
			.addClass(priorityPresenter.cssClass);
	$("#wt_td_status").text(statusPresenter.txt);
	$("#wt_td_status").removeClass(
			"ticketNew ticketOpen ticketClosed ticketReplied").addClass(
			statusPresenter.cssClass);
	$("#wt_td_description").html(ticket.DescriptionHtml);
	if (ticket.Due) {
		var dateBuffer = new Date();
		dateBuffer.setTime(ticket.Due.replace(/[^0-9]/ig, ""));
		$("#wt_td_deadline").text(
				$.datepicker.formatDate('yy-mm-dd', dateBuffer));
	} else
		$("#wt_td_deadline").text("");

}

// corresponds to the login button onclick() event
function login() {
	var email = $("#wt_login_email").get()[0].value;
	var pwd = $("#wt_login_password").get()[0].value;
	LoginAndDoStuff(domain, email, pwd);
}

//
function logout() {
	eraseCookie(sessionKey);
	injectHtml();
}

// injects the customer dashboard html snippet to a predefined div with id
// #worketc_customer_dashboard
function injectHtml() {
	var html = " <div id='wt_dashboard' class='wt_dashboard_main ui-widget'> \
    <div id='wt_login' style='width:100%'> \
    <table style='width:30%;' cellpadding='0' cellspacing='0' class='ui-widget-content' > \
    <caption style='text-align:left' class='ui-widget-header'>Enter your Worketc username and password here</caption> \
    <tr><th>E-mail :</th><td><input type='text' style='width:95%;' id='wt_login_email' value='dev@agilemates.com' /></td></tr> \
    <tr><th>Password :</th><td><input type='password' style='width:95%' id='wt_login_password' value='770913'/></td></tr> \
    <tr><td colspan='2' align='right'><button onclick='javascript:login(); return false;'>Sign in</button></td></tr> \
    </table> \
    </div> \
    <div id='wt_customer_info' style='width:100%; display:none;' > \
		<div id='wt_nav' class='ui-corner-all ui-widget-header''> \
			<ul id='wt_nav_bar'> \
				<li ><a href='#'>Your details</a></li> \
				<li><a href='#'>Projects</a></li>\
				<li><a href='#'>Support Cases</a></li>\
				<li><a href='#'>Accounts</a></li>\
			</ul>\
			</div>\
	        <div id='wt_customer_data' class='ui-corner-all ui-widget-content customerdata' style='float:left; width:45%'> \
			<h3>Welcome <span id='wt_customer_name'> &nbsp;&nbsp;</span> \
        	<a href='#' style='text-decoration:none; font-size:small' onclick='javascript:logout(); return false;'>Sign out</a></h3> \
			<h4>This is the customer portal for <b><span id='wt_business_name'/></b></h4> \
            <h4>Our records show your contact details as:</h4> \
            <table id='wt_customer_data_tb'> \
            		<tr><th>Companies:</th><td id='wt_cd_companies'></td></tr> \
            </table> <br/>\
            <div>Are these details correct?&nbsp; \
            		<button onclick='return false;'>Yes</button>&nbsp; \
            		<button onclick='return false;'>No</button> \
            </div> \
        </div>\
        <div id='wt_support_cases'  class='ui-widget-content ui-corner-all customerdata' style='display:none; float: right; width:45%'> \
            <h3>Support cases for you</span></h3> \
            <table id='wt_tickets'><tr><th>Ticket name</th><th>Priority</th><th>Status</th></tr></table> \
			<ul id='pagination'></ul> \
        </div> \
    </div> \
    		<div id='wt_td_dialog' title='Ticket details' style='display:none'> \
	             <table> \
						<tr><th>Name</th><td id='wt_td_name'/></tr> \
	             		<tr><th>Deadline</th><td id='wt_td_deadline'/></tr> \
	             		<tr><th>Priority</th><td id='wt_td_priority'/></tr> \
	             		<tr><th>Status</th><td id='wt_td_status'/></tr> \
	             		<tr><th>Description</th><td id='wt_td_description'/></tr> \
			</div> \
</div>"

	$("#worketc_customer_dashboard").html(html);
}

// this code is attached to document onload event and is called whenever the
// document loads compleatly
// This just calls injectHtml()
$(function() {
	injectHtml();
	$( "button", ".wt_dashboard_main" ).button();
});
